// ajaxHelper
function AjaxHelper() {
    this.ajax = function(url, type, dataType, data, callback, errorback) {
        $.ajax({
            url:  url,
            type: type,
            dataType: dataType,
            data: data,
            beforeSend: function () {
                $.showLoading();
            },
            success: callback,
            error: errorback || function(xhr, errorType, error) {
                $.hideLoading();
                alert('Ajax request error, errorType: ' + errorType +  ', error: ' + error)
            }
        });         
    }
};
AjaxHelper.prototype.get = function(url, data, callback, errorback) {
    this.ajax(url, 'GET', 'json', data, callback, errorback)
};
AjaxHelper.prototype.post = function(url, data, callback, errorback) {
    this.ajax(url, 'POST', 'json', data, callback, errorback)
};
AjaxHelper.prototype.put = function(url, data, callback, errorback) {
    this.ajax(url, 'PUT', 'json', data, callback, errorback)
};
AjaxHelper.prototype.delete = function(url, data, callback, errorback) {
    this.ajax(url, 'DELETE', 'json', data, callback, errorback)
};
AjaxHelper.prototype.jsonp = function(url, data, callback, errorback) {
    this.ajax(url, 'GET', 'jsonp', data, callback, errorback)
};
AjaxHelper.prototype.constructor = AjaxHelper;

function simpleTpl( tpl ) {
    tpl = $.isArray( tpl ) ? tpl.join( '' ) : (tpl || '');
    return {
        store: tpl,
        _: function() {
            var me = this;
            var tempStr="";
            var res=arguments[1]||"";
            if(arguments.length==2&&typeof res=="object"&&typeof res.length=="undefined"){
                var tempStr="";
                var argStr=arguments[0];
                for(var i in res){
                    tempStr+=' '+i+'=\"'+res[i]+'\"';
                }
                if(/^<img/.test(argStr)&&argStr.lastIndexOf("/")!=-1){
                    tempStr=argStr.substring(0,argStr.lastIndexOf("/"))+tempStr+'/>';
                }else{
                    tempStr=argStr.substring(0,argStr.length-1)+tempStr+'>';
                }
                me.store += tempStr;
            }else{
                $.each(arguments,function( index, value) {
                    me.store += value;
                });
            }
            return this;
        },
        toString: function() {
            return this.store;
        }
    };
};

$(function () {
    var common = {
        // 分类列表
        categories: '',
        init: function () {
            this.event();
        },
        event: function () {
            // 获取cookie
            this.getCookie();
            // 点击导航
            this.bottomTabClick();
            // 获取分类
            this.getCategories();
            // 点击发布
            this.releaseClick();
        },
        // 获取分类列表
        getCategories: function () {
            var self = this , ajax = new AjaxHelper();
            ajax.get('/categories', '', function (data) {
                $.hideLoading();
                if (!data) $.toptips('分类获取失败！');
                self.categories = data;
            });
        },
        getCookie: function () {
            var index = $.fn.cookie('tabbarIndex') || 0;
            $('#tab-bottom').find('.weui_tabbar_item').removeClass('weui_bar_item_on');
            $('#tab-bottom').find('.weui_tabbar_item').eq(index).addClass('weui_bar_item_on');
        },
        // 点击发布按钮
        releaseClick: function() {
            var self = this, t = '';
            // 发布按钮点击
            $('#release-btn').on('click', function () {
                t = '';
                if (self.categories != "") {
                    t += '<div class="release-type">';
                    for( var i = 0; i < self.categories.length; i++ ) {
                        t += '<a href="/article/add/'+self.categories[i].slug+'">'+self.categories[i].name+'</a>';
                    }
                    t += '</div>';
                }
                // 获取用户名
                var username = $('#username').val().trim();
                // 存在跳转发布页
                if (username && username != "") {
                    $.modal({
                        title: "发布类型",
                        text: t.toString(),
                        buttons: [
                            { text: "取消", className: "default release-cancel"},
                        ]
                    });
                    $('.release-cancel').css('color','#ef4f4f');
                }
                // 不存在重新填写用户名
                else {
                    $.prompt("请填写您在机械社区的用户名 !", "您的昵称", function(name) {
                        var ajax = new AjaxHelper();
                        var reg = /^[0-9a-zA-Z\u4e00-\u9fa5_]{2,8}$/;
                        if (reg.test(name) != true) {
                            $.toptips('用户名只能为中文、英文、_和数字 ！');
                        } else {
                            ajax.post('/user/add', {username: name}, function (data) {
                                $.hideLoading();
                                if (data.result == 1) {
                                    $.toptips('用户名设置成功，快去发布吧 ！','ok');
                                    setTimeout(function () {
                                        // 刷新当前页面
                                        location.reload();
                                    }, 1000)
                                } else {
                                    $.toptips('用户名已存在，换个试试吧 ！');
                                }
                            });
                        }                        
                    }, function() {
                      //取消操作
                    });
                }
            });
        },
        // 底部导航按钮点击
        bottomTabClick: function () {
            $('#tab-bottom').find('.weui_tabbar_item_a').off('click').on('click', function(e) {
                var id = $(this).attr('data-id'),
                    href = $(this).attr('data-path');
                if (id) {
                    $.fn.cookie('tabbarIndex', id, { path: '/' });
                    window.location.href = href;
                }
            });
        }
    }
    common.init();    
})